<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>复制产品</title>
<script type="text/javascript">
    Ext.onReady(function () {
        var gridHeight = 270;
        var id = Ext.create('Ext.form.field.Hidden', {
            name: 'id'
        });
        //单品或套装
        var isSuit = Ext.create('Ext.form.RadioGroup', {
            //name: 'is_suit',
            fieldLabel: '套装',
            anchor: '100%',
            vertical: false,
            items: [
                {boxLabel: '是', name: 'is_suit', inputValue: 1},
                {boxLabel: '否', name: 'is_suit', inputValue: 0}
            ]
        });

        isSuit.on("change", function (radioGroup, checkedRadio) {
            /*if (isSuit.getChecked()[0].inputValue==1){
             if (!productComponentsGrid.isVisible()){
             //productComponentsGrid.setVisible(true);
             //copyProductWin.setHeight(copyProductWin.getHeight() + gridHeight);
             }
             }else{
             //productComponentsGrid.setVisible(false);
             //copyProductWin.setHeight(copyProductWin.getHeight() - gridHeight);
             }*/
        })

        //为销售或组装
        var isSale = Ext.create('Ext.form.RadioGroup', {
            fieldLabel: '销售',
            columns: 2,
            anchor: '100%',
            vertical: false,
            items: [
                {boxLabel: '是', inputValue: 1, name: 'is_sale'},
                {boxLabel: '否', inputValue: 0, name: 'is_sale'}
            ]
        });

        //供应商
        var vendor = Ext.create('Ext.form.ComboBox', {
            store: vendorStore,
            fieldLabel: '供应商',
            allowBlank: false,
            blankText: "供应商必须选择",
            valueField: 'id',
            displayField: 'name',
            name: 'vendor_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            editable: false,
            loadingText: '搜索中...',
            anchor: '97%',
            //pageSize: 10,
            readOnly: false,
            minChars: 0,
            editable: false
        });

        var number = Ext.create('Ext.form.field.Text', {
            fieldLabel: '编号',
            allowBlank: false,
            blankText: "编号不能为空",
            name: 'number',
            anchor: '95%'
        });

        //品牌相关combobox
        //品牌
        var brand = Ext.create('Ext.form.ComboBox', {
            store: brandStore,
            fieldLabel: '品牌',
            allowBlank: false,
            blankText: "品牌必须选择",
            valueField: 'id',
            displayField: 'name',
            name: 'brand_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            editable: false,
            loadingText: '搜索中...',
            anchor: '95%',
            readOnly: false,
            minChars: 0
        });

        //产品
        var productType = Ext.create('Ext.form.ComboBox', {
            store: productTypeStore,
            fieldLabel: '产品类别',
            allowBlank: false,
            blankText: "类别必须选择",
            valueField: 'id',
            displayField: 'name',
            name: 'product_type_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            editable: false,
            loadingText: '搜索中...',
            anchor: '94%',
            readOnly: false,
            minChars: 0
        });

        var name = Ext.create('Ext.form.field.Text', {
            fieldLabel: '名称',
            allowBlank: false,
            blankText: "产品名称不能为空",
            name: 'name',
            anchor: '96%'
        });

        var spec = Ext.create('Ext.form.field.Text', {
            fieldLabel: '规格',
            name: 'spec',
            anchor: '95%'
        });

        var unit = Ext.create('Ext.form.field.Text', {
            fieldLabel: '单位',
            name: 'unit',
            anchor: '95%'
        });

        var unitPrice = Ext.create('Ext.form.field.Number', {
            fieldLabel: '销售单价',
            name: 'unit_price',
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            nanText: "您输入的不是数字",
            anchor: '95%'
        });

        var minQuantity = Ext.create('Ext.form.field.Number', {
            fieldLabel: '最少',
            name: 'min_quantity',
            allowBlank: false,
            allowDecimals: false,
            minValue: 0,
            minValue: 0,
            maxValue: 10000,
            anchor: '95%'
        });

        var maxQuantity = Ext.create('Ext.form.field.Number', {
            fieldLabel: '最多',
            name: 'max_quantity',
            allowBlank: false,
            allowDecimals: false,
            minValue: 0,
            minValue: 0,
            maxValue: 10000,
            anchor: '95%'
        });

        var costPrice = Ext.create('Ext.form.field.Number', {
            fieldLabel: '成本单价',
            name: 'cost_price',
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            decimalPrecision: 10,
            minValue: 0,
            value: 0,
            anchor: '95%'
        });

        var taxPrice = Ext.create('Ext.form.field.Number', {
            fieldLabel: '含税单价',
            name: 'tax_price',
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            decimalPrecision: 10,
            minValue: 0,
            value: 0,
            anchor: '95%'
        });

        var desc = Ext.create('Ext.form.TextArea', {
            fieldLabel: '描述',
            height: 60,
            name: 'description',
            anchor: '97%'
        });

        //销售类型产品对应Grid
        saleTypePricesDS.getProxy().extraParams.id = <%=@productId%>;
        saleTypePricesDS.load();

        //销售类型产品价格对应Grid
        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        var saleTypePricesGrid = Ext.create('Ext.grid.Panel', {
            store: saleTypePricesDS,
            columns: [Ext.create('Ext.grid.RowNumberer'),
                {
                    header: '销售类型',
                    dataIndex: 'name',
                    width: 190
                }, {
                    header: '单价',
                    dataIndex: 'unit_price',
                    align: 'right',
                    renderer: Ext.util.Format.numberRenderer('0,000.00'),
                    field: Ext.create('Ext.form.field.Number', {
                        allowBlank: false,
                        allowDecimals: true,
                        minValue: 0
                    }),
                    width: 100
                }],
            width: 400,
            height: 285,
            anchor: '100%',
            frame: true,
            title: '销售类型与产品价格列表',
            //frame: true,
            //plugins: checkColumn,
            plugins: [cellEditing]//这里应该是单击就可以修改的意思。因为默认是要双击的。
        });

        //--------------------------------------------------------------------------
        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
            store: productAllInfoStore,
            emptyText: '请选择...',
            displayField: 'name',
            loadingText: '搜索中...',
            anchor: '100%',
            pageSize: 10,
            minChars: 0,
            listConfig: {
                loadingText: 'Searching...',
                getInnerTpl: function () {
                    return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
                }
            }
        });

        productCBB.on('select', function (combo, record, index) {
            var sm = productComponentsGrid.getSelectionModel();
            var records = sm.getSelection();
            var subItemRecord = records[0];
            //alert(saleOrderItemRecord);
            if (!subItemRecord) {
                return false;
            }
            //Ext.MessageBox.alert("提示",rec.get('number'));
            if (isDuplicateByProduct(productComponentsDS, record[0].get('id'), subItemRecord.id)) {
                //删除当前记录
                productComponentsDS.remove(subItemRecord);
            } else {
                subItemRecord.set('number', record[0].get('number'));
                subItemRecord.set('spec', record[0].get('spec'));
                subItemRecord.set('unit', record[0].get('unit'));
                subItemRecord.set('unit_price', record[0].get('unit_price'));
                subItemRecord.set('amount', record[0].get('unit_price'));
                subItemRecord.set('quantity', 1);
                subItemRecord.set('discount', 1.0);
                subItemRecord.set('product_id', record[0].get('id'));
                subItemRecord.set('is_suit', record[0].get('is_suit'));
            }
        });

        //产品Grid Store
        productComponentsDS.removeAll();
        productComponentsDS.getProxy().extraParams.id = <%=@productId%>;
        //productComponentsDS.load();

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        //生成要订单的产品的Grid
        var productComponentsGrid = Ext.create('Ext.grid.Panel', {
            store: productComponentsDS,
            plugins: [cellEditing],
            columns: [Ext.create('Ext.grid.RowNumberer'),
                {
                    header: '产品名称',
                    dataIndex: 'name',
                    field: productCBB,
                    width: 370
                }, {
                    header: '产品ID',
                    dataIndex: 'product_id',
                    width: 50,
                    hidden: false
                }, {
                    header: '产品编号',
                    dataIndex: 'number',
                    width: 95
                }, {
                    header: '规格',
                    dataIndex: 'spec',
                    width: 60
                }, {
                    header: '单位',
                    dataIndex: 'unit',
                    width: 60
                }, {
                    header: '数量',
                    align: 'right',
                    dataIndex: 'quantity',
                    field: Ext.create('Ext.form.field.Number', {
                        allowBlank: false,
                        allowDecimals: false,
                        minValue: 0
                    }),
                    width: 60
                }, {
                    header: '单价',
                    dataIndex: 'unit_price',
                    align: 'right',
                    renderer: Ext.util.Format.numberRenderer('0,000.00'),
                    width: 65
                }, {
                    header: '套装?',
                    dataIndex: 'is_suit',
                    width: 50
                }],
            selModel: Ext.create('Ext.selection.CheckboxModel'),
            width: 910,
            height: 280,
            loadMask: true,
            //frame: true,
            //title: '进货品种列表',
            //frame: true,
            //plugins: checkColumn,
            clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
            tbar: [
                {
                    text: '添加产品',
                    iconCls: 'addItem',
                    handler: function () {
                        var record = Ext.ModelManager.create({
                            product_name: '请选择产品'
                        }, productComponentsGrid.getStore().model);
                        productComponentsDS.insert(0, record);
                    }
                },
                {
                    text: '删除',
                    iconCls: 'remove',
                    handler: function () {
                        var sm = productComponentsGrid.getSelectionModel();
                        var records = sm.getSelection();
                        cellEditing.cancelEdit();
                        productComponentsDS.remove(records);
                    }
                }
            ]
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
            text: '提交',
            tooltip: '保存产品信息。',
            iconCls: 'icon-save',
            handler: function () {
                if (vendor.getRawValue() === vendor.getValue()) {
                    vendor.reset();
                }
                if (productComponentsFormPanel.form.isValid()) {
                    var allJsonStr = productComponentsFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);

                    var pricesJsonStr = gridStoreToJson(saleTypePricesDS);
                    allJsonStr = allJsonStr + ",\"prices\":" + pricesJsonStr;

                    //只有套装产品，才有附属产品
                    if (isSuit.getChecked()[0].inputValue == 1) {
                        var productsJsonStr = gridStoreToJson(productComponentsDS, rejectKeyArray);
                        if (productComponentsDS.getCount() == 0 || productsJsonStr === "") {
                            Ext.MessageBox.show({
                                title: '提示',
                                msg: "您还没有选择有效的产品或选择的产品数量为0！",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.INFO
                            });
                            return;
                        }
                        allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                    } else {
                        allJsonStr = allJsonStr + "}";
                    }

                    this.disable();
                    Ext.Ajax.request({
                        url: '/product/copyToNew',
                        success: function (result, request) {
                            if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "复制产品信息，操作成功！",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.INFO
                                });
                                copyProductWin.destroy();
                            } else if (Ext.JSON.decode(result.responseText).info.indexOf("相同") > -1) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: Ext.JSON.decode(result.responseText).info,
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                                submitButton.enable();
                            } else {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: Ext.JSON.decode(result.responseText).info,
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                                copyProductWin.destroy();
                            }
                        },
                        failure: function (result, request) {
                            Ext.MessageBox.show({
                                title: '消息',
                                msg: "通讯失败，请从新操作",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                            copyProductWin.destroy();
                        },
                        method: 'POST',
                        params: {
                            data: Ext.JSON.encode(allJsonStr),
                            authenticity_token: authToken.getValue()
                        }
                    });
                }
            }
        });

        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
            text: '关闭',
            tooltip: '关闭当前窗口，并且当前复制的信息不能保存。',
            iconCls: 'exit',
            handler: function () {
                copyProductWin.destroy();
            }
        });

        var productComponentsFormPanel = Ext.create('Ext.form.Panel', {
            fieldDefaults: {
                labelWidth: 60,
                labelAlign: 'right'
            },
            width: '930',
            frame: true,
            url: '/product/copyToNew',
            method: 'GET',
            reader: Ext.create('Ext.data.reader.Json', {
                model: 'ProductModel',
                root: 'root'
            }),
            //defaultType: 'textfield',
            items: [
                {
                    layout: 'column', xtype: 'container',
                    items: [
                        {
                            columnWidth: .5,
                            layout: 'anchor', xtype: 'container',
                            items: [vendor, name, {
                                layout: 'column', xtype: 'container',
                                items: [
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [isSuit]
                                    },
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [isSale]
                                    }
                                ]
                            }, {
                                layout: 'column', xtype: 'container',
                                items: [
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [productType]
                                    },
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [brand]
                                    }
                                ]
                            }, {
                                layout: 'column', xtype: 'container',
                                items: [
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [unit]
                                    },
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [unitPrice]
                                    }
                                ]
                            }, {
                                layout: 'column', xtype: 'container',
                                items: [
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [number]
                                    },
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [spec]
                                    }
                                ]
                            }, {
                                layout: 'column', xtype: 'container',
                                items: [
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [minQuantity]
                                    },
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [maxQuantity]
                                    }
                                ]
                            }, {
                                layout: 'column', xtype: 'container',
                                items: [
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [costPrice]
                                    },
                                    {
                                        columnWidth: .5,
                                        layout: 'anchor', xtype: 'container',
                                        items: [taxPrice]
                                    }
                                ]
                            }, desc]
                        },
                        {
                            columnWidth: .5,
                            layout: 'anchor', xtype: 'container',
                            items: [saleTypePricesGrid]
                        }
                    ]
                },
                productComponentsGrid,
                id
            ],
            buttons: [submitButton, closeButton]
        });
        productComponentsFormPanel.render('edit_product');
        //
        //productComponentsGrid.on('edit', afterEdit, this );

        function afterEdit(editor, obj, options) {
            // execute an XHR to send/commit data to the server, in callback do (if successful):
            if (obj.field == "quantity" || obj.field == "unit_price" || obj.field == "discount") {
                if (obj.record.get('quantity') > 0 && obj.record.get('unit_price') > 0) {
                    obj.record.set('amount', obj.record.get('quantity') * 10000 * obj.record.get('unit_price') * obj.record.get('discount') / 10000);
                } else {
                    obj.record.set('amount', 0);
                }
            }
        }

        productComponentsFormPanel.getForm().reset();

        productComponentsFormPanel.form.load({
            url: '/product/edit?id=' + <%=@productId%>,
            method: 'GET',
            waitMsg: '正在载入数据...',
            success: function (form, action) {
                //debugger;
                if (action.result.data.is_suit === 1) {
                    isSuit.setValue({is_suit: [1]});
                } else {
                    isSuit.setValue({is_suit: [0]});
                }

                if (action.result.data.is_sale === 1) {
                    isSale.setValue({is_sale: [1]});
                } else {
                    isSale.setValue({is_sale: [0]});
                }
                productComponentsDS.load();
            },
            failure: function (form, action) {
                Ext.MessageBox.alert('提示信息', '信息加载失败');
            }
        });

    })
</script>
</head>
<body>
<div id="edit_product"></div>
</body>
</html>